<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-12-22
 * Time: 下午4:19
 */

namespace Common\Org\Upload;
use Common\Org\Chat\WeiXin;
use Common\Org\Qrcode\LogoQRMake;
use Think\Image;


class Upload {
    public function upload($alias,$uid=false,$filetype='',$input='',$area='',$weixin=false){
        if(empty($alias)){
            return array('info'=>'非法操作','status'=>0);
        }

        empty($input) && $input = 'photo';

        if (!empty($_FILES) && $alias != ''){
            $do = base64_decode($alias);//还原附件配置别名编码
            $darr = get_attach($do, $uid);//获取附件配置

            if(empty($darr)){
                return array('info'=>'config error','status'=>0);
            }

            $upload = new UploadFile(); // 实例化上传类
            $upload->maxSize = intval($darr['max_size']) * 1024 * 1024;//最大允许上传文件大小

            ////保存规则处理
            $upload->saveRule = 'uniqid';

            $upload->savePath = $darr['dir_path']; // 设置附件上传目录,原图片路径
            $upload->uploadReplace = true;

            //设置附件上传类型
            if($filetype){
                $upload->allowExts = explode(',', $filetype);
            }else{
                $upload->allowExts = explode(',', $darr['extension']);
            }

            mk_dir($darr['dir_path'], 0777);//若不存在，则创建文件目录

            if (!$upload->upload()){
                //上传错误提示错误信息
                return array('info'=>$upload->getErrorMsg(),'status'=>0);
            }else{
                // 上传成功 获取上传文件信息
                $info = $upload->getUploadFileInfo();

                //缩略图尺寸处理
                $thumb = false;
                $prefixArr = array();
                if(!empty($darr['extend']) && strstr($darr['extend'],'*'))
                {
                    $w_h = $this->getWh($darr['extend'],$prefixArr);
                    $thumb = true;
                }

                $filesArr = array();
                foreach($info as $key=>$value){
                    $savename = trim($info[$key]['savename'], '.');//保存的文件名

                    if($weixin){
                        //微信上传处理
                        $wx = new WeiXin(C('AppID'),C('AppSecret'));
                        $result = $wx->uploadImageTextImg($darr['dir_path'].$info[$key]['savename']);

                        if(empty($result['url'])){
                            return array('info'=>$result['errmsg'].':'.$result['errcode'],'status'=>0);
                        }

                        //$result['url'] = 'http://mmbiz.qpic.cn/mmbiz/eVHcklOJLCtGydaicuRtkRsv61u2rQAITuZDBbpQgSHDtGxhfoJQu9uLWyhGR49B2a2jmnkM8xxzIvWp14UnwiaQ/0 src=';
                    }

                    //生成相应的缩略图
                    if($thumb){
                        $savename = $this->thumb($w_h,$darr['dir_path'],$savename);
                    }

                    $filesArr['files'][$key]['savename'] = $savename;//20140526修改
                    $filesArr['files'][$key]['name'] = trim($info[$key]['name'], '.');//20140526修改
                    $filesArr['files'][$key]['size'] = trim($info[$key]['size'], '.');//20140526修改
                    $filesArr['files'][$key]['type'] = trim($info[$key]['type'], '.');//20140526修改
                    $filesArr['files'][$key]['url'] = trim($darr['img_root'] . $savename, '.');//20140526修改
                    $filesArr['files'][$key]['bigUrl'] = trim($darr['img_root'] .'big_'. $savename, '.');//20140526修改

                    $filesArr['files'][$key]['weixin'] = $weixin ? $result['url'] : '';

                    $is_pic = in_array(strtolower($filetype),array('jpg','jpeg','gif','png','bmp'));
                    $extend = $darr['extend'];
                    if(empty($extend) || !$is_pic){
                        $filesArr['files'][$key]['smallUrl'] = $filesArr['files'][$key]['bigUrl'] = $filesArr['files'][$key]['midUrl'] = trim($darr['img_root'] . $savename, '.');
                    }else{
                        $filesArr['files'][$key]['bigUrl'] = trim($darr['img_root'] .'1_'. $savename, '.');//20151203修改
                        //中图
                        if(in_array('2_',$prefixArr)){
                            $filesArr['files'][$key]['midUrl'] = trim($darr['img_root'] .'2_'. $savename, '.');//20140526修改
                        } else {
                            $filesArr['files'][$key]['midUrl'] = trim($darr['img_root'] . $savename, '.');//20140526修改
                        }
                        //小图
                        if(in_array('3_',$prefixArr)){
                            $filesArr['files'][$key]['smallUrl'] = trim($darr['img_root'] .'3_'. $savename, '.');//20140526修改
                        } else {
                            $filesArr['files'][$key]['smallUrl'] = trim($darr['img_root'] . $savename, '.');//20140526修改
                        }
                    }
                }
            }

            return array('info'=>'ok','files'=>$filesArr['files'],'input'=>$input,'area'=>$area,'status'=>1);
        }
        else
        {
            return array('info'=>'没有上传文件','status'=>0);
        }
    }

    /**
     *根据地址生成图片
     * @param $updo
     * @param $uid
     * @param $location
     * @return mixed
     */
    public function uploadImgForUrl($updo,$uid='',$imgUrl){
        if($updo && $imgUrl){
            $do = base64_decode($updo);//还原附件配置别名编码
            $darr = get_attach($do,$uid);//获取附件配置
            $data = file_get_contents($imgUrl);
            mk_dir($darr['dir_path'], 0777);
            $save_face_name = time().mt_rand().'.png';
            $org_dir = rtrim($darr['dir_path'],'/').'/';
            @file_put_contents($org_dir.$save_face_name,$data);//原图

            $info['status'] = 1;
            $info['info'] = '上传成功';
            $info['file'] = $save_face_name;

            return $info;
        }
    }

    /**
     * 文件重命名
     * @param $updo 附件配置别名
     * @param $uid 用户ID
     * @param $old 原文件名
     * @param $new 修改之后的文件名
     */
    public function rename($alias,$old,$new,$uid=false){
        if(empty($alias) || empty($old) || empty($new)) {
            $info['status'] = 0;
            $info['info'] = '参数错误';
            return $info;
        }

        $darr = get_attach($alias, $uid);

        $dir = rtrim($darr['dir_path'],'/').'/';//路径

        //$new = iconv('UTF-8','GB2312',$new);
        if(IS_WIN){
            $new = iconv('GB2312','UTF-8',$new);
            $old = iconv('UTF-8','GB2312',$old);
        }

        $res = @rename($dir.$old,$dir.$new);//重命名
        @rename($dir.'big_'.$old,$dir.'big_'.$new);//重命名
        @rename($dir.'mid_'.$old,$dir.'mid_'.$new);//重命名
        @rename($dir.'small_'.$old,$dir.'mid_'.$new);//重命名

        if($res){
            return array('status'=>1,'info'=>'ok');
        } else {
            return array('status'=>0,'info'=>'重命名失败');
        }
    }

    /**
     * 生成二维码
     * @param $updo
     * @param $uid
     * @param $url
     * @param int $role
     * @return mixed
     */
    public function creadeQrcode($uid){
        if(empty($uid)) return false;

        $darr = get_attach('qrcode',$uid);
        mk_dir($darr['dir_path'], 0777);

        $url = SITE_URL.'?iuid='.$uid;
        $png = new LogoQRMake($url,false,$darr['dir_path'],6,'H',1);
        $save_face_name = $png->images();

        //缩略图尺寸处理
        $thumb = false;
        if(!empty($darr['extend']) && strstr($darr['extend'],'*'))
        {
            $w_h = $this->getWh($darr['extend']);

            $thumb = true;
        }

        //生成相应的缩略图
        if($thumb){
            $save_face_name = $this->thumb($w_h,$darr['dir_path'],$save_face_name);
        }

        return $save_face_name;
    }

    private function getWh($extend,&$prefixArr=array()){
        $w_h = array();
        $i = 0;
        $extendArr = explode('|',$extend);//标准尺寸
        foreach($extendArr as $val){
            $size = explode('*', $val);
            $w_h[$i]['w'] = $size[0];
            $w_h[$i]['h'] = $size[1];
            $prefixArr[] = $w_h[$i]['prefix'] = ($i+1).'_';
            $i++;
        }

        unset($i,$j,$k,$val,$extendArr);

        return $w_h;
    }

    /**
     * 缩略图处理
     * @param $alias 附件配置别名
     * @param $w_h
     * @param $dir_path
     * @param $savename
     * @param $filetype
     */
    private function thumb($w_h,$dir_path,$savename,$filetype=''){
        //生成相应的缩略图
        $exif = @exif_read_data(rtrim($dir_path,"/")."/".$savename);
        if(isset($exif['Orientation'])){
            //数码相机拍照图片处理
            $uploadDir = ROOT_PATH."Application/Common/Org/Upload/";
            require_once($uploadDir."WideImage_Operation_ExifOrient.class.php");
            require_once($uploadDir."WideImage/WideImage.php");
            $image = \WideImage::load(rtrim($dir_path,"/")."/".$savename);
            $image->exifOrient($exif['Orientation'])->saveToFile(rtrim($dir_path,"/")."/".$savename);
        }

        foreach($w_h as $v){
            if(empty($v['w']) || empty($v['h'])) continue;
            $Image = new Image(2);
            $Image->open(rtrim($dir_path,"/")."/".$savename);
            $Image->thumb($v['w'],$v['h'],3);
            $newImg = rtrim($dir_path,"/")."/".$v['prefix'].$savename;
            $Image->save($newImg,null,100);

            unset($Image,$newImg);
        }
        unset($w_h,$dir_path,$exif,$image);

        return $savename;
    }
} 